package com.fxg;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class ZkTestDemo {

    @Autowired
    CuratorFramework curatorFramework;


    //添加一个节点
    @Test
    public void test01() throws Exception {
        //添加持久节点
        String path = curatorFramework.create().forPath("/curator-node");
        //添加临时序号节点，ephemeral 短暂的 sequential 顺序的
        String path1 = curatorFramework.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/curator-node", "some-data".getBytes());
        System.out.println(String.format("curator create node :%s  successfully.",path));
        System.in.read();

    }

    //查看一个节点的数据
    @Test
    public void testGetData() throws Exception {
        byte[] bytes = curatorFramework.getData().forPath("/curator-node");
        System.out.println(new String(bytes));
    }


    //修改一个节点的数据
    @Test
    public void testSetData() throws Exception {
        curatorFramework.setData().forPath("/curator-node","changed!".getBytes());
        byte[] bytes = curatorFramework.getData().forPath("/curator-node");
        System.out.println(new String(bytes));
    }

    //创建一个节点，顺便创建它的父节点
    @Test
    public void testCreateWithParent() throws Exception {
        String pathWithParent="/node-parent/sub-node-1";
        String path = curatorFramework.create().creatingParentsIfNeeded().forPath(pathWithParent);
        System.out.println(String.format("curator create node :%successfully.",path));
    }

    //删除一个节点
    @Test
    public void testDelete() throws Exception {
        String pathWithParent="/node-parent";

        curatorFramework.delete().guaranteed().deletingChildrenIfNeeded().forPath(pathWithParent);
    }

}
